﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using DiscussProject.Models;
using System.Linq.Expressions;

namespace DiscussProject.Controllers
{
    public class ArticlesController : Controller
    {
        private ArticleContext db = new ArticleContext();
        private UserContext userdb = new UserContext();

        // GET: Articles
        public ActionResult Index()
        {
            return View(db.Articles.ToList());
        }

        // GET: Articles/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Article article = db.Articles.Find(id);
            if (article == null)
            {
                return HttpNotFound();
            }
            return View(article);
        }

        // GET: Articles/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Articles/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        // 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Title,CreateTime,Content,Like,ViewNum,Category")] Article article)
        {
            

            if (ModelState.IsValid)
            {
                db.Articles.Add(article);
                db.SaveChanges();
                return RedirectToAction("Index2");
            }

            return View(article);
        }

        public ActionResult Create2()
        {
            List<SelectListItem> itemlist = new List<SelectListItem>();
            itemlist.Add(new SelectListItem() { Value = "分享", Text = "分享" });
            itemlist.Add(new SelectListItem() { Value = "讨论", Text = "讨论" });
            itemlist.Add(new SelectListItem() { Value = "学术", Text = "学术" });
            itemlist.Add(new SelectListItem() { Value = "娱乐", Text = "娱乐" });
            itemlist.Add(new SelectListItem() { Value = "交友", Text = "交友" });
            SelectList select = new SelectList(itemlist, "Value", "Text", "分享");
            ViewBag.select = select;
            return View();
        }

        //POST: Articles/Create
        //为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        //更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create2([Bind(Include = "Title,Content,Category")] Article article)
        {
            article.Author= db.Users.Find((int)Session["Id"]);
            article.CreateTime = DateTime.Now;
            if (ModelState.IsValid)
            {
                db.Articles.Add(article);
                db.SaveChanges();
                return RedirectToAction("Index2");
            }

            return View(article);
        }

        // GET: Articles/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Article article = db.Articles.Find(id);
            if (article == null)
            {
                return HttpNotFound();
            }
            return View(article);
        }

        public ActionResult Edit2(int? id)
        {

            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Article article = db.Articles.Find(id);
            if (article == null)
            {
                return HttpNotFound();
            }
            List<SelectListItem> itemlist = new List<SelectListItem>();

            itemlist.Add(new SelectListItem() { Value = "分享", Text = "分享" });
            itemlist.Add(new SelectListItem() { Value = "讨论", Text = "讨论" });
            itemlist.Add(new SelectListItem() { Value = "学术", Text = "学术" });
            itemlist.Add(new SelectListItem() { Value = "娱乐", Text = "娱乐" });
            itemlist.Add(new SelectListItem() { Value = "交友", Text = "交友" });
            SelectList select = new SelectList(itemlist, "Value", "Text", article.Category);
            ViewBag.select = select;
            ViewBag.content = article.Content;
            return View(article);
        }

        // POST: Articles/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        // 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Title,Content,Category")] Article article)
        {
            article.Author = db.Users.Find((int)Session["Id"]);
            article.CreateTime = DateTime.Now;
            if (ModelState.IsValid)
            {
                db.Entry(article).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(article);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit2([Bind(Include = "Id,Title,Content,Category")] Article article)
        {

            article.UserId = (int)Session["Id"];
            article.CreateTime = DateTime.Now;
                if (ModelState.IsValid)
                {
                    db.Entry(article).State = EntityState.Modified;
                    db.SaveChanges();
                    return Redirect("/Articles/Detail2?id="+article.Id);
                }
            return View(article);
        }

        // GET: Articles/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Article article = db.Articles.Find(id);
            if (article == null)
            {
                return HttpNotFound();
            }
            return View(article);
        }

        // POST: Articles/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Article article = db.Articles.Find(id);
            db.Articles.Remove(article);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        public ViewResult Index2()
        {
            int id = (int)Session["id"];
            ViewBag.User = db.Users.Find(id);
            return View(db.Articles.ToList());
        }
        public ActionResult Detail2(int id)
        {
            int uid = (int)Session["id"];
            ViewBag.myinfo = db.Users.Find(uid);
            var model = db.Articles.Find(id);
            model.Author = db.Users.Find(model.UserId);
            var comments =  from item in db.Comments where model.Id.Equals(item.Post.Id) select item;
            var tmp_com = comments.ToList();
            for (int i = 0; i < tmp_com.Count; i++)
            {
                tmp_com[i].User = db.Users.Find(tmp_com[i].UserId);
            }
            ViewData["comments"] = tmp_com;
            return View(model);
        }
        public JsonResult FindByCategory(string category)
        {
            var result = from item in db.Articles where item.Category.Equals(category) select item;
            var tmp = result.ToArray();
            for (int i = 0; i < tmp.Length; i++)
            {
                var author = db.Users.Find(tmp[i].UserId);
                tmp[i].Author = author;
            }
            return Json(tmp, JsonRequestBehavior.AllowGet);
        }
        public JsonResult FindByTitleLike(string title)
        {
            var result =  from item in db.Articles where item.Title.Contains(title) select item;
            var tmp = result.ToArray();
            for (int i = 0; i < tmp.Length; i++)
            {
                var author = db.Users.Find(tmp[i].UserId);
                tmp[i].Author = author;
            }
            return Json(tmp, JsonRequestBehavior.AllowGet);
        }
        public JsonResult FindALL()
        {
            var datas = db.Articles;
            foreach (var item in datas)
            {
                item.Author = db.Users.Find(item.UserId);

            }
            return Json(datas, JsonRequestBehavior.AllowGet);
        }
        public ActionResult SubmitComment(FormCollection collection)
        {
            Comment data = new Comment();
            data.Content = Request.Form["content"];
            data.CreateTime = DateTime.Now;
            data.Post = db.Articles.Find(Convert.ToInt32(Request.Form["articleId"]));
            User user = db.Users.Find((int)Session["Id"]);
            data.User = user;
            db.Comments.Add(data);
            db.SaveChanges();
            return Redirect("/Articles/Detail2?id=" + Request.Form["articleId"]);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
